package com.cavasmonitor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.cavasmonitor.db.CavasDao;
import com.cavasmonitor.to.TemperaturaTo;
import com.cavasmonitor.to.UsuarioTo;
import com.cavasmonitor.util.Session;
import com.cavasmonitor.util.TemperaturesUpdater;

import android.os.Bundle;
import android.app.AlertDialog;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SimpleAdapter;

public class ConfiguracionActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.configuracion);

		ImageButton img = (ImageButton) findViewById(R.id.btnHome);

		img.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent i = new Intent(ConfiguracionActivity.this,
						OpcionesActivity.class);
				startActivityForResult(i, 1);
			}
		});

		img = (ImageButton) findViewById(R.id.btnExit);

		img.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				new AlertDialog.Builder(ConfiguracionActivity.this)
						.setTitle(R.string.msg_salir)
						.setMessage(R.string.msg_logout)
						.setPositiveButton(R.string.msg_aceptar,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										Session.usuario = null;
										Intent i = new Intent(
												ConfiguracionActivity.this,
												MainActivity.class);
										startActivityForResult(i, 1);
									}
								})
						.setNegativeButton(R.string.msg_cancelar, null).show();

			}
		});

		CavasDao dao = new CavasDao(ConfiguracionActivity.this);
		dao.open();

		EditText input = (EditText) findViewById(R.id.inputIp);
		input.setText(dao.getValueConfig("IP"));

		InputFilter[] filters = new InputFilter[1];
		filters[0] = new InputFilter() {
			@Override
			public CharSequence filter(CharSequence source, int start, int end,
					Spanned dest, int dstart, int dend) {
				if (end > start) {
					String destTxt = dest.toString();
					String resultingTxt = destTxt.substring(0, dstart)
							+ source.subSequence(start, end)
							+ destTxt.substring(dend);
					if (!resultingTxt
							.matches("^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) {
						return "";
					} else {
						String[] splits = resultingTxt.split("\\.");
						for (int i = 0; i < splits.length; i++) {
							if (Integer.valueOf(splits[i]) > 255) {
								return "";
							}
						}
					}
				}
				return null;
			}
		};

		input.setFilters(filters);

		input = (EditText) findViewById(R.id.inputCiclo);
		input.setText(dao.getValueConfig("CICLO"));

		input = (EditText) findViewById(R.id.inputTelefono);
		input.setText(dao.getValueConfig("PHONE"));

		dao.close();

		Button btn = (Button) findViewById(R.id.btnGuardar);
		btn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				EditText input = (EditText) findViewById(R.id.inputIp);
				String ip = input.getText().toString().trim();

				input = (EditText) findViewById(R.id.inputCiclo);
				String ciclo = input.getText().toString().trim();

				input = (EditText) findViewById(R.id.inputTelefono);
				String phone = input.getText().toString().trim();

				if (ip.length() == 0) {
					new AlertDialog.Builder(ConfiguracionActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_cfg_ip_req)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else if (ip.split("\\.").length != 4) {
					new AlertDialog.Builder(ConfiguracionActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_cfg_ip_bad)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else if (ciclo.length() == 0) {
					new AlertDialog.Builder(ConfiguracionActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_cfg_ciclo_req)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else if (phone.length() == 0) {
					new AlertDialog.Builder(ConfiguracionActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_cfg_phone_req)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else {

					CavasDao dao = new CavasDao(ConfiguracionActivity.this);
					dao.open();

					dao.updateValueConfig("IP", ip);
					dao.updateValueConfig("CICLO", ciclo);
					dao.updateValueConfig("PHONE", phone);

					if (TemperaturesUpdater.clockTimer != null) {
						TemperaturesUpdater.clockTimer.cancel();
						TemperaturesUpdater.clockTimer = null;
					}
					
					@SuppressWarnings("unused")
					TemperaturesUpdater timer = new TemperaturesUpdater(ConfiguracionActivity.this);

					new AlertDialog.Builder(ConfiguracionActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_cfg_succ)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();

					dao.close();

					Intent i = new Intent(ConfiguracionActivity.this,
							ConfiguracionActivity.class);
					startActivityForResult(i, 1);

				}
			}
		});
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent i;
		switch (item.getOrder()) {
		case Session.M_USUARIOS:
			i = new Intent(ConfiguracionActivity.this, UsuariosActivity.class);
			startActivityForResult(i, 1);
			return true;
		case Session.M_CFG:
			i = new Intent(ConfiguracionActivity.this,
					ConfiguracionActivity.class);
			startActivityForResult(i, 1);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		if (Session.usuario.getRol() == UsuarioTo.Rol.ADMINISTRADOR) {
			getMenuInflater().inflate(R.menu.main, menu);
		} 
		return true;
	}

}
